package com.authine.cloudpivot.web.api.secondopen.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.authine.cloudpivot.engine.api.model.organization.RoleModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.secondopen.domain.AjaxResult;
import com.authine.cloudpivot.web.api.secondopen.modules.CompanyVO;
import com.authine.cloudpivot.web.api.secondopen.service.PortalService;
import com.authine.cloudpivot.web.api.secondopen.utils.PortalPageUtil;
import com.authine.cloudpivot.web.api.secondopen.vo.*;
import com.authine.cloudpivot.web.api.utils.StringUtils;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: brookpeng
 * @Date: 2021/9/13 16:50
 */
@Api(value = "二开接口", tags = "门户接口")
@RestController
@RequestMapping("/api/portal")
public class PortalController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(PortalController.class);

    @Autowired
    private PortalService portalService;

    /**
     * 获取会议室使用信息
     * @return
     */
    @RequestMapping(value = "/getMeetingInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value = "获取会议室使用信息", notes = "获取会议室使用信息")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "date", value = "查询日期", dataType = "String", required = true)
    )
    public ResponseResult<Map<String,List<MeetingInfoVO>>> getMeetingInfo(@RequestParam(value = "date", required = true) String date,
                                                                     @RequestParam(value = "sourceId", required = false) String sourceId,
                                                                     @RequestParam(value = "companyId", required = true) String companyId,
                                                                     @RequestParam(value = "thismonth",required = true) Boolean thismonth,
                                                                     @RequestParam(value = "thisweek" ,required = true) Boolean thisweek,
                                                                     @RequestParam(value = "meetroom", required = false) String meetroom){
        String userId = getUserId();
        Map<String,List<MeetingInfoVO>> meetingRoomInfo = new HashMap<>();
        String tableName = getBizObjectFacade().getTableName("HYGL");
        String tableName2 = getBizObjectFacade().getTableName("meetingRoom");
        meetingRoomInfo = portalService.getMeetingRoomInfo(userId, date, tableName, sourceId, tableName2, companyId, thismonth, thisweek, meetroom);
        if (CollectionUtil.isNotEmpty(meetingRoomInfo)) {
            return getOkResponseResult(meetingRoomInfo, "获取会议室使用信息成功");
        } else {
            return getErrResponseResult(meetingRoomInfo, 999999L, "获取会议室使用信息失败");
        }
    }

    /**
     * 获取当前选择会议室占用时间信息
     * @param meetingRoomName
     * @return
     */
    @RequestMapping(value = "/getSelectedMeetingRoomSchedules", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "获取当前选择会议室占用时间信息", notes = "获取当前选择会议室占用时间信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "meetingRoomName", value = "会议室名称", dataType = "String", required = false)
    })
    public ResponseResult<List<String>> getSelectedMeetingRoomSchedules(@RequestParam(value = "meetingRoomName", required = false) String meetingRoomName) {
        List<String> selectedMeetingRoomSchedules = portalService.getSelectedMeetingRoomSchedules(meetingRoomName);
        return getOkResponseResult(selectedMeetingRoomSchedules, "获取当前选择会议室占用时间信息成功");
    }

    /**
     * 申请会议时间校验
     * @param meetingRoomName
     * @param startTime
     * @param endTime
     * @return 返回null时校验通过，否则返回冲突的会议时间段
     */
    @RequestMapping(value = "/checkMeetingTimes", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "申请会议时间校验", notes = "申请会议时间校验")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "meetingRoomName", value = "会议室名称", dataType = "String", required = true),
            @ApiImplicitParam(name = "startTime", value = "会议开始时间", dataType = "String", required = true),
            @ApiImplicitParam(name = "endTime", value = "会议结束时间", dataType = "String", required = true)
    })
    public ResponseResult<String> checkMeetingTimes(@RequestParam(value = "meetingRoomName", required = true) String meetingRoomName,
                                                    @RequestParam(value = "startTime", required = true) String startTime,
                                                    @RequestParam(value = "endTime", required = true) String endTime) {
        String res = portalService.checkMeetingTimes(meetingRoomName, startTime, endTime);
        return getOkResponseResult(res, "获取申请会议时间校验结果成功");
    }

    @RequestMapping(value = "/getUserMeetingSchedules", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "用户会议计划获取", notes = "用户会议计划获取")
    public ResponseResult<List<MeetingSchedulesVO>> getUserMeetingSchedules() {
        String tableName = getBizObjectFacade().getTableName("HYGL");
        String userId = getUserId();
        List<MeetingSchedulesVO> userMeetingSchedules = portalService.getUserMeetingSchedules(userId, tableName);
        return getOkResponseResult(userMeetingSchedules, "获取用户会议计划成功");
    }

    @RequestMapping(value = "/getUserFileTree", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "文件管理列表获取", notes = "文件管理列表获取")
    public ResponseResult<List<FileTreeVO>> getUserFileTree(@RequestParam(value = "schemaCode", required = false) String schemaCode){
        String userId = getUserId();
        List<FileTreeVO> fileTreeVOs = portalService.getUserFileTreeService(userId, schemaCode);
        return getOkResponseResult(fileTreeVOs, "文件管理列表获取成功");
    }

    @RequestMapping(value = "/getUserFileName", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "文件获取", notes = "文件获取")
    public ResponseResult<FileListVO> getUserFileName(@RequestParam(value = "instanceName", required = true) String instanceName,
                                                        @RequestParam(value = "page", required = false) String page,
                                                        @RequestParam(value = "size", required = false) String size) {
        int pageNum =0 ;
        int pageSize = 1;
        if (!StringUtils.isEmpty(page)) {
            pageNum = Integer.parseInt(page);
            if (pageNum == 0) {
                pageNum += 1;
            }
        }
        if (!StringUtils.isEmpty(size)) {
            pageSize = Integer.parseInt(size);
        }
        String userId = getUserId();
        FileListVO fileListVO = new FileListVO();
        List<FileVO> fileTreeVOs = portalService.getUserFileNameService(userId, instanceName);
        int size1 = fileTreeVOs.size();
        List resultList = PortalPageUtil.startPage(fileTreeVOs, pageNum, pageSize);
        fileListVO.setTotal(size1);
        fileListVO.setFileVOs(resultList);
        return getOkResponseResult(fileListVO, "文件获取成功");
    }

    @RequestMapping(value = "/getUserFileNameLike", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "文件获取", notes = "文件获取")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "模糊查询文件名", dataType = "String", required = false),
            @ApiImplicitParam(name = "startTime", value = "会议开始时间", dataType = "String", required = true),
            @ApiImplicitParam(name = "endTime", value = "会议结束时间", dataType = "String", required = true)
    })
    public ResponseResult<FileListVO> getUserFileNameLike(@RequestParam(value = "fileName", required = false) String fileName,
                                                          @RequestParam(value = "searchTimeFrom", required = false) String searchTimeFrom,
                                                          @RequestParam(value = "searchTimeTo", required = false) String searchTimeTo,
                                                          @RequestParam(value = "page", required = false) String page,
                                                          @RequestParam(value = "size", required = false) String size,
                                                          @RequestParam(value = "type", required = false) String type) {
        int pageNum = 1;
        int pageSize = 1;
        if (!StringUtils.isEmpty(page)) {
            pageNum = Integer.parseInt(page);
            if (pageNum < 0) {
                pageNum = 1;
            }
        }
        if (!StringUtils.isEmpty(size)) {
            pageSize = Integer.parseInt(size);
        }
        String userId = getUserId();
        List<FileVO> fileTreeVOs = portalService.getUserFileNameLikeService(userId, fileName, searchTimeFrom, searchTimeTo, type);
        int resultSize = fileTreeVOs.size();
        List resultPage = PortalPageUtil.startPage(fileTreeVOs, pageNum, pageSize);
        FileListVO fileListVO = new FileListVO();
        fileListVO.setTotal(resultSize);
        fileListVO.setFileVOs(resultPage);
        return getOkResponseResult(fileListVO, "文件获取成功");
    }

    @RequestMapping(value = "/getHYJYTree", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "文件管理列表获取", notes = "文件管理列表获取")
    public ResponseResult<List<FileTreeVO>> getHYJYTree(){
        String userId = getUserId();
        List<FileTreeVO> fileTreeVOs = portalService.getHYJYTreeService(userId);
        return getOkResponseResult(fileTreeVOs, "文件管理列表获取成功");
    }

    @RequestMapping(value = "/getHYJYName", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "文件获取", notes = "文件获取")
    public ResponseResult<FileListVO> getHYJYName(@RequestParam(value = "key", required = true) String key,
                                                      @RequestParam(value = "page", required = false) String page,
                                                      @RequestParam(value = "size", required = false) String size) {
        int pageNum = 1;
        int pageSize = 1;
        if (!StringUtils.isEmpty(page)) {
            pageNum = Integer.parseInt(page);
            if (pageNum <= 0) {
                pageNum = 1;
            }
        }
        if (!StringUtils.isEmpty(size)) {
            pageSize = Integer.parseInt(size);
        }
        String userId = getUserId();
        FileListVO fileListVO = new FileListVO();
        List<FileVO> fileTreeVOs = portalService.getHYJYNameService(userId, key);
        int size1 = fileTreeVOs.size();
        List resultList = PortalPageUtil.startPage(fileTreeVOs, pageNum, pageSize);
        fileListVO.setTotal(size1);
        fileListVO.setFileVOs(resultList);
        return getOkResponseResult(fileListVO, "文件获取成功");
    }

    @RequestMapping(value = "/getMeetingRoomsByLoginUserDepartments", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "会议室按公司获取", notes = "会议室按公司获取")
    public ResponseResult<List<MeetingRoomVO>> getMeetingRoomsByLoginUserDepartments() {
        String userId = getUserId();
        String tableName = getBizObjectFacade().getTableName("meetingRoom");
        List<String> ids = new ArrayList<>();
        ids.add(userId);
        Map<String, List<RoleModel>> userRole = getOrganizationFacade().getRolesByUserIds(ids);
        boolean isAdministrator = false;
        isAdministrator = isOrganizationAdministrator(userId, userRole, isAdministrator);
        List<MeetingRoomVO> meetingRoomsByLoginUserDepartments = portalService.getMeetingRoomsByLoginUserDepartments(userId, tableName, isAdministrator);
        return getOkResponseResult(meetingRoomsByLoginUserDepartments, "会议室按公司获取成功");
    }

    @RequestMapping(value = "/getCompanyListByLoginUserRole", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "获取登录用户可选则的公司列表", notes = "获取登录用户可选则的公司列表")
    public ResponseResult<List<CompanyVO>> getCompanyListByLoginUserRole() {
        List<String> ids = new ArrayList<>();
        String loginUserId = getUserId();
        ids.add(loginUserId);
        Map<String, List<RoleModel>> userRole = getOrganizationFacade().getRolesByUserIds(ids);
        boolean isAdministrator = false;
        isAdministrator = isOrganizationAdministrator(loginUserId, userRole, isAdministrator);
        List<CompanyVO> companyListByLoginUserRole = portalService.getCompanyListByLoginUserRole(isAdministrator, loginUserId);
        return getOkResponseResult(companyListByLoginUserRole, "获取登录用户可选则的公司列表成功");
    }

    private boolean isOrganizationAdministrator(String loginUserId, Map<String, List<RoleModel>> userRole, boolean isAdministrator) {
        String mainCorpId = getMainCorpId();
        UserModel admin = getOrganizationFacade().getUserByUserNameAndCorpId("admin", mainCorpId);
        String adminId = admin.getId();
        if (loginUserId.equals(adminId)) {
            isAdministrator = true;
        } else {
            for (Map.Entry<String, List<RoleModel>> entry : userRole.entrySet()) {
                for (RoleModel roleModel : entry.getValue()) {
                    String roleName = roleModel.getName();
                    switch (roleName) {
                        case "集团管理人员":
                            isAdministrator = true;
                            break;
//                        case "公司管理人员":
//                            isAdministrator = true;
//                            break;
                        default:
                            isAdministrator = false;
                    }
                    if (isAdministrator) {
                        break;
                    }
                }
                if (isAdministrator) {
                    break;
                }
            }
        }
        return isAdministrator;
    }

    /**
     * 根据公司id获取会议室列表
     */
    @GetMapping("/getlistroom")
    public AjaxResult getListMeetingRoom(String companyId){
        if (StringUtils.isEmpty(companyId)){
            return  AjaxResult.error("参数为空");
        }
        List<Map<String, Object>> listMeetingRoomByCompanyId = portalService.getListMeetingRoomByCompanyId(companyId);
        return AjaxResult.success(listMeetingRoomByCompanyId);
    }
}